﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace gui {
    /// <summary>
    /// Interaction logic for ConsolePane.xaml 
    /// (The console UI element on the Algorithm Registry Tab)
    /// </summary>
    public partial class ConsolePane : UserControl {

        private static event guiOnConsoleWriteEvent OnConsoleWrite;
        private static bool consoleEmpty = true;

        public ConsolePane() {
            InitializeComponent();
            ConsoleConnect._Dispatcher = this.Dispatcher;
            this.DataContext = ConsoleConnect.Instance;

            ConsoleConnect.Write("Network Model has not been initialised yet.");

            // Add event listener for scroller
            OnConsoleWrite += ScrollToBottom;
        }

        // Write To Console
        public static void Write(string str) {
            WriteToConsole(str, false);
        }

        // WriteLine string To Console
        public static void WriteLine(string str) {
            WriteToConsole(str, true);
        }

        // WriteLine black To Console
        public static void WriteLine() {
            WriteToConsole("", true);
        }

        // Connect to ConsoleConnect
        private static void WriteToConsole(string str, bool newLine) {
            if (consoleEmpty) {
                ConsoleConnect.Clear();
                consoleEmpty = false;
            }
            if (newLine) ConsoleConnect.WriteLine(str);
            else ConsoleConnect.Write(str);

            if (OnConsoleWrite != null) OnConsoleWrite();   // Notify scroller of a new write
        }

        // Automatically scroll to the bottom of the Console
        private void ScrollToBottom() {
            Dispatcher.Invoke(
            DispatcherPriority.Normal,
            (Action)delegate() { ScrollerXAML.ScrollToBottom(); }
            );
        }
    }
}
